package jzoffer;

import java.util.*;

/**
 * @author MaoLin Wang
 * @date 2020/10/12 12:48 下午
 */
public class _38字符串的排列 {
    public static String[] permutation(String s) {
        if (s == null || "".equals(s)){
            return new String[0];
        }
        char[] charArray = s.toCharArray();
        Arrays.sort(charArray);

        Set<String>res=new HashSet<>();
        boolean[] marked=new boolean[charArray.length];
        char[] temp=new char[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            marked[i]=true;
            temp[0]=charArray[i];
            dfs(res,marked,charArray,charArray.length,0,temp);
            marked[i]=false;
        }
        return res.toArray(new String[0]);
    }

    private static void dfs(Set<String> res, boolean[] marked, char[] charArray, int length,int index,char[] temp) {
        if (index>=length-1){
            res.add(String.valueOf(temp));
            return;
        }
        for (int i = 0; i < length; i++) {
            if (!marked[i]){
                marked[i]=true;
                temp[++index]=charArray[i];
                dfs(res,marked,charArray,length,index,temp);
                marked[i]=false;
                index--;
            }
        }
    }

    public static void main(String[] args) {
        for (String abc : permutation("abc")) {
            System.out.println(abc);
        }
    }
}